//
//  ComponentCell.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/17.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView

protocol ComponentCellDelegate: class {
    func insertComponent(component: CodableComponentOfMaterial)
    func deleteComponent(at index: Int)
}

class ComponentCell: UITableViewCell, UICollectionViewDelegate, UICollectionViewDataSource {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var addButton: UIButton!
    @IBOutlet weak var constraint: NSLayoutConstraint!
    var edited = true {
        didSet {
            if edited == false {
                constraint.constant = 8
            }
        }
    }
    
    var items = [CodableComponentOfMaterial]()
    weak var delegate: ComponentCellDelegate?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        collectionView.delegate = self
        collectionView.dataSource = self

        collectionView.register(UINib(nibName: "ComponentInsideCell", bundle: nil), forCellWithReuseIdentifier: "ComponentInsideCell")
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("++++++\(items.count)")
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let row = indexPath.row
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ComponentInsideCell", for: indexPath) as! ComponentInsideCell
        cell.nameLabel.text = items[row].name
        cell.percentLabel.text = "\(items[row].percent)"
        cell.deleteButton.isHidden = !edited
        cell.deleteButton.addTarget(self, action: #selector(deleteBtTapped(_:)), for: .touchUpInside)
        return cell
    }
    
    @IBAction func addButtonTapped(_ button: UIButton!) {
        showAlert()
    }
    @objc func deleteBtTapped(_ button: UIButton!) {
        let point = button.convert(CGPoint.zero, to: collectionView)
        guard let indexPath = collectionView.indexPathForItem(at: point) else {
            return
        }
        items.remove(at: indexPath.row)
        delegate?.deleteComponent(at: indexPath.row)
        collectionView.performBatchUpdates({
            collectionView.deleteItems(at: [indexPath])
        }, completion: nil)
    }
    
    func showAlert() {
        let appearance = SCLAlertView.SCLAppearance(showCloseButton: false, shouldAutoDismiss: true, hideWhenBackgroundViewIsTapped: true)
        let alert = SCLAlertView(appearance: appearance)
        let nameTF = alert.addTextField("成分名称")
        let percentTF = alert.addTextField("成分分量(0 ~ 100)")
        percentTF.keyboardType = .numberPad
        alert.addButton("确定") {
            guard let name = nameTF.text.nilIfEmpty, let _percent = percentTF.text.nilIfEmpty else {
                return
            }
            guard let percent = Double(string: _percent), percent < 100 else {
                return
            }
            let component = CodableComponentOfMaterial(name: name, percent: "\(percent)")
            self.items.append(component)
            print(self.items)
            self.delegate?.insertComponent(component: component)
            self.collectionView.performBatchUpdates({
                self.collectionView.insertItems(at: [IndexPath(row: self.items.count-1, section: 0)])
            }, completion: nil)
        }
        alert.showEdit("设置成分信息", subTitle: "")
    }
    
}
